import { createSlice, createAsyncThunk, createSelector } from '@reduxjs/toolkit'
import uuid from 'uuid-v4'

const initialState = [
  {
    id: 1,
    name: '吃饭',
    done: true
  },
  {
    id: 2,
    name: '睡觉',
    done: false
  },
  {
    id: 3,
    name: '打豆豆',
    done: true
  }
]

const deleteTodo = async (val) => {
  // 这里可以模拟接口请求
  return new Promise((resolve) => {
    setTimeout(() => {
      // resolve中返回的数据就是接口请求的数据
      // let data = {}
      resolve(val)
    }, 1000)
  })
}

// 这里就需要一个异步函数，有成功和失败的状态
export const delTodo2 = createAsyncThunk('todo/del', async (val) => {
  // console.log("val", val);
  // 这里应该是接收接口返回的数据，然后传递给extraReducers的addCase函数
  // 然后让他在接口请求正确的时候，进行下一步操作
  const data = await deleteTodo(val)
  return data
})

export const todoSlice = createSlice({
  name: 'todo',
  initialState,
  reducers: {
    addTodo: (state, { payload }) => {
      const todo = {
        id: uuid(),
        name: payload.name,
        done: false
      }
      return [todo, ...state]
      // state.unshift(todo);
    },
    delTodo: (state, { payload }) => {
      console.log('payload', payload.id)
      return state.filter((item) => item.id !== payload.id)
    }
  },
  extraReducers(builder) {
    builder
      .addCase(delTodo2.pending, (state) => {
        console.log('🚀 ~ 进行中！')
      })
      .addCase(delTodo2.fulfilled, (state, { payload }) => {
        console.log('🚀 ~ fulfilled', payload)
        return state.filter((item) => item.id !== payload.id)
      })
      .addCase(delTodo2.rejected, (state, err) => {
        console.log('🚀 ~ rejected', err)
      })
  }
})

export const { addTodo, delTodo } = todoSlice.actions

export default todoSlice.reducer

function getList(state) {
  // console.log('asd', state)
  return state.todo
}
export const getToList = createSelector(getList, (state) => state)

// 这个写法就不行，因为这里的state是整个的store，根本不能知道是具体的哪个数据
// 这里的state和reducers中的state作用域不一样，并不是一个概念
// export const getToList = createSelector(
//   (state) => state,
//   (state) => state
// )
